//
//  ActivateViewController.m
//  Guazi
//
//  Created by koolearn on 11-6-23.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "ActivateViewController.h"
#import "TextFieldCell.h"
#import "ButtonCell.h"
#import "StringUtil.h"
#import "TwitterClient.h"
#import "GuaziAppDelegate.h"


#define kTagActivateKey 101
#define kTagNickName 102
#define kTagPassword 103
#define kTagPhone 301


@interface ActivateViewController(private)
- (void) setValueByTextField:(UITextField*)textField;
@end

@implementation ActivateViewController


@synthesize activeCode;
@synthesize nickname;
@synthesize password;
@synthesize phone;

@synthesize textField;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.textField = nil;
    }
    return self;
}


- (void)dealloc
{
    [activeCode release];
    [nickname release];
    [password release];
    [phone release];
    [textField release];
    [super dealloc];
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


#pragma mark - tool operations

- (void) close
{
    NSInteger selectedIndex = [GuaziAppDelegate getAppDelegate].tabBarController.selectedIndex;
    UINavigationController* nav = [[GuaziAppDelegate getAppDelegate].tabBarController.viewControllers objectAtIndex:selectedIndex];
    [nav dismissModalViewControllerAnimated:YES];
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"激活";
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"放弃" 
                                                                               style:UIBarButtonItemStylePlain 
                                                                              target:self action:@selector(close)] autorelease];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.activeCode = nil;
    self.nickname = nil;
    self.password = nil;
    self.phone = nil;
    self.textField = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ( section == 0 ) {
        return 3;
    }
    else if ( section == 1 ) {
        return 1;
    }
    else if ( section == 2 ) {
        return 1;
    }
    else if ( section == 3 ) {
        return 1;
    }
    else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    if ( section == 0 ) {
        NSString* s = @"cell0";
        TextFieldCell* cell = (TextFieldCell*) [tableView dequeueReusableCellWithIdentifier:s];
        if ( !cell ) {
            cell = [[[TextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:s] autorelease];
        }
        
        if ( row == 0 ) {
            [cell updateWithDelegate:self tag:kTagActivateKey];
        }
        else if ( row == 1 ) {
            [cell updateWithDelegate:self tag:kTagNickName];
        }
        else if ( row == 2 ) {
            [cell updateWithDelegate:self tag:kTagPassword];
            [cell setSecurity:YES];
        }
        return cell;
    }
    else if ( section == 1 ) {
        NSString* s = @"cell1";
        ButtonCell* cell = (ButtonCell*) [tableView dequeueReusableCellWithIdentifier:s];
        if ( !cell ) {
            cell = [[[ButtonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:s] autorelease];
        }
        
        [cell setTitle:@"激活"];
        UIImage* image = [[UIImage imageNamed:@"button_green.png"] stretchableImageWithLeftCapWidth:8 topCapHeight:0];
        [cell setImage:image imagePressed:nil];
        return cell;
    }
    else if ( section == 2 ) {
        NSString* s = @"cell0";
        TextFieldCell* cell = (TextFieldCell*) [tableView dequeueReusableCellWithIdentifier:s];
        if ( !cell ) {
            cell = [[[TextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:s] autorelease];
        }
        [cell updateWithDelegate:self tag:kTagPhone];
        return cell;
    }
    else if ( section == 3 ) {
        NSString* s = @"cell1";
        ButtonCell* cell = (ButtonCell*) [tableView dequeueReusableCellWithIdentifier:s];
        if ( !cell ) {
            cell = [[[ButtonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:s] autorelease];
        }
        
        [cell setTitle:@"重新发送"];
        UIImage* image = [[UIImage imageNamed:@"button_green.png"] stretchableImageWithLeftCapWidth:8 topCapHeight:0];
        [cell setImage:image imagePressed:nil];
        return cell;
    }
    
    return nil;
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if ( section == 0 ) {
        return @"激活码已经通过短信发送给您。请在下框中输入激活码、昵称、密码。";
    }
    else if (section == 2) {
        return @"如果您在5分钟内没有收到激活码，或者您的激活码丢失，请在下框中输入手机号，然后按“重新发送”。";
    }
    else {
        return nil;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ( section == 0 ) {
        return 60;
    }
    else if ( section == 2 ) {
        return 100;
    }
    else {
        return 0;
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate


- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ( indexPath.section == 0 || indexPath.section == 2 ) {
        return nil;
    }
    else {
        return indexPath;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    User* user = [GuaziAppDelegate getAppDelegate].user;
    
    if ( section == 1 && row == 0 ) {
        //激活
        if ( textField ) {
            [self setValueByTextField:textField];
            BOOL result = [TwitterClient activateSync:user.userId activateCode:self.activeCode screenName:self.nickname password:self.password];
            if ( !result ) {
                [GuaziAppDelegate showAlert:@"抱歉，激活用户失败"];
                return;
            }
            
            user.screenName = self.nickname;
            user.password = self.password;
            user.state = kUserStateValid;
            [user updateDB:NO withName:NO withAccount:YES];
            [GuaziAppDelegate showAlert:@"您的用户帐户已经成功激活"];
            
            NSInteger index = [GuaziAppDelegate getAppDelegate].tabBarController.selectedIndex;
            UINavigationController* nav = [[GuaziAppDelegate getAppDelegate].tabBarController.viewControllers objectAtIndex:index];
            [nav dismissModalViewControllerAnimated:YES];
        }
    }
    else if ( section == 3 && row == 0 ) {
        //重新发送
        [self setValueByTextField:textField];
        BOOL result = [TwitterClient registerSync:user.userId name:user.name password:user.password];
        if ( !result ) {
            [GuaziAppDelegate showAlert:@"抱歉，发送服务器请求失败"];
            return;
        }
        
        user.state = kUserStateUnopen;
        [user updateDB:NO withName:NO withAccount:NO];
        [GuaziAppDelegate showAlert:@"已经通过手机短信给您发送了激活码。请填写激活码以完成注册过程。"];
    }
}


#pragma mark - TextFieldCell delegate

- (NSString*) label:(NSInteger)tag 
{
    if ( tag == kTagActivateKey ) {
        return @"激活码";
    }
    else if ( tag == kTagNickName ) {
        return @"昵称";
    }
    else if ( tag == kTagPassword ) {
        return @"密码";
    }
    else {
        return @"";
    }
}

- (NSString*) text:(NSInteger)tag
{
    if ( tag == kTagPhone ) {
        return [GuaziAppDelegate getAppDelegate].user.name;
    }
    else {
        return @"";
    }
}

- (CGFloat) labelWidth:(NSInteger)tag
{
    if ( tag == kTagActivateKey ) {
        return 60.0f;
    }
    else if ( tag == kTagNickName ) {
        return 60.0f;
    }
    else if ( tag == kTagPassword ) {
        return 60.0f;
    }
    else {
        return 0.0f;
    }
}

- (NSString*) textFieldPlaceHolder:(NSInteger)tag
{
    if ( tag == kTagActivateKey ) {
        return @"请输入激活码";
    }
    else if ( tag == kTagNickName ) {
        return @"请输入昵称";
    }
    else if ( tag == kTagPassword ) {
        return @"请输入密码";
    }
    else if ( tag == kTagPhone ) {
        return @"请输入手机号";
    }
    return @"";
}


- (void) setValueByTextField:(UITextField*)field
{
    NSInteger tag = field.tag;
    if ( tag == kTagActivateKey ) {
        self.activeCode = [field.text trim];
    }
    else if ( tag == kTagNickName ) {
        self.nickname = [field.text trim];
    }
    else if ( tag == kTagPassword ) {
        self.password = [field.text trim];
    }
    else if ( tag == kTagPhone ) {
        self.phone = [field.text trim];
    }
}


- (void)textFieldDidBeginEditing:(UITextField *)field
{
    self.textField = field;
}


- (void) textFieldDidEndEditing:(UITextField *)field
{
    [self setValueByTextField:field];
}




@end
